package com.thy.controller;

import com.thy.common.MessageTemplate;
import com.thy.common.Result;
import com.thy.config.WechatConf;
import com.thy.pojo.U;
import com.thy.service.UService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class UController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WechatConf wechatConf;
    @Autowired
    private UService userService;

    MessageTemplate messageTemplate = new MessageTemplate();
    @RequestMapping("/tes")
    @Async
    public Object sendMess(){
        int water = 100;
        //所有open_id
        List<U> userList=userService.selectUserByWater(water);
        userList.forEach(item->{
        userService.updateUserById(item.getId());
        // 设置模板id
        messageTemplate.setTemplateId("KCWgi0xagqVyczZOT9_Ro3JQoodmQndrOneIUt4V-8s");
        // 设置接收用户openId
        messageTemplate.setToUser(item.getLeader().getOpenid());
        //点击详情跳转的地址
        messageTemplate.setUrl("http://www.baidu.com");

        //设置模板dada参数
        messageTemplate.getData().put("first", MessageTemplate.initData("停水用户信息,请注意查收！\n", "#79C5C3"));
        messageTemplate.getData().put("username", MessageTemplate.initData(item.getUserName(), "#00CD00"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        messageTemplate.getData().put("time", MessageTemplate.initData(simpleDateFormat.format(new Date())+"\n", "#79C5C3"));
        messageTemplate.getData().put("phone", MessageTemplate.initData(item.getUserTelephone(), "#00CD00"));
        messageTemplate.getData().put("address", MessageTemplate.initData(item.getUserAddress(), "#00CD00"));
        messageTemplate.getData().put("remark", MessageTemplate.initData("点击详情可查看信息", "#79C5C3"));

        Result result = restTemplate.postForObject(String.format(WechatConf.PUSH_MESSAGE_URL, wechatConf.getAccessToken()),
                    messageTemplate, Result.class);
        });
        //调用微信接口，发送模板消息

        return null;
    }
}
